import $ from 'jquery'
import jsPlumb from 'jsPlumb'
import {menu_panel,switch_page,get_attr_menu} from "./ui"
import od from "./components"
import File from '../cls/File'
import Procedure from '../cls/Procedure'
import Page from '../cls/Page'
import {make_vue,listen_props_change,listen_content_change,listen_data_change} from "./builder"
import {update_procedure,save_procedure} from "./procedure"
import Dialog from '../widget/Dialog'
import axios from 'axios'

function eventOnDeleteDown(ev,project) {
    if(project.scene == "view") {       //删除当前选中的元素节点
        if(project.cur_dom !== null) {
            project.cur_dom.remove()
        }
    }else if(project.scene == "file") { //删除当前选中的文件节点
        if(project.procedure_file === null) {    //选中的是视图文件
            if(project.manager.current !== null) {
                project.manager.remove(project.manager.current.name,function(file){
                    //TODO：流程文件删除需要做的处理
                })
            }
        }else {                                 //如果选中的是流程文件
            project.manager.current.file.removeChild(project.procedure_file)
            project.procedure_file = null
            project.manager.toView()
        }
    }else if(project.scene === "procedure") {      //删除流程流程元素节点
        if(project.cur_procedure !== null) {
            jsPlumb.removeAllEndpoints(project.cur_procedure)
            $("#" + project.cur_procedure).remove()
            project.cur_procedure = null
        }
    }
}

export function onKeyDown(project) {
    $(document).on("keydown", function(e) {
        if(e.keyCode === 46) {
            eventOnDeleteDown(e, project)
        }
    })
}
export function onNewClick(project) {
    $("#newProcedure").on("click",(e) => {
        project.scene = "file"
        let name = prompt("请输入流程名")
        if(name != null && name != "") {
            let file = new Procedure(name,1)
            project.manager.current.file.addChild(file)
            project.manager.toView()
            project.procedure_file = file
            update_procedure("procedurebox",project)
        }else {
            alert("流程名称不能为空");
        }
    })
    $("#newView").on("click",(e) => {
        project.scene = "file"
        let name = prompt("请输入视图名")
        if(name != null && name!= "") {
            let file = new File(name,0)
            let page = new Page(name,file,{})
            project.manager.add(page)
            project.manager.switch(name,(page)=>{
                project.procedure_file = null
                switch_page(project)
                make_vue(project)
            })
        }else {
            alert("视图名称不能为空")
        }
    })
    $("#newData").on("click",function(e) {
        let dataBox  = $("<div></div>")
        dataBox.addClass("data-box-item")
        dataBox.append("<div class = 'data-box-label'><input type='text' placeholder='变量名'/></div>")
        dataBox.append('<div class = "data-box-value"><input type="text" placeholder="变量值"/></div>')
        $("#vuedata").append(dataBox)
    })
}
export function onFileChange(project){
    $("#filelist").on("click",".file-top>li",(e)=>{
        let name = $(e.target).attr("data-name")
        project.manager.switch(name,(file)=>{
            project.cur_procedure = null
            switch_page(project)
            make_vue(project)
        })
    })

    $("#filelist").on("click",".sub-list>li",(e)=>{
        e.stopPropagation()
        let name = $(e.target).attr("data-name")
        let parent = $(e.target).parent('ul').attr("data-file-view")
        project.manager.switch(parent,(file)=>{
            let child = file.getChild(name)
            $("ul[data-file-view="+parent+"]>li[data-name="+name+"]").addClass("active")
            project.cur_procedure = child
            switch_page(project)
            make_vue(project)
            update_procedure("procedurebox",project)
        })

    })

}
export function onProcedureSave(project) {
    $("#saveProcess").on("click",function(e) {
        save_procedure(project)
    })
}
export function onComponentClick(project) {
    $(".preview-viewer").on("click",".vm",function(e){
        e.stopPropagation()
        project.scene = "view"
        let av = $(this).attr("action-view")
        let x = e.pageX
        project.cur_dom = this
        $(".od-dialog").remove()
        menu_panel({
            width:"360px",
            margin:"auto",
            left: x + 80 + "px"
        },od[av],e.target)
        listen_props_change(project)
    })
    $(".preview-viewer").on("click",".nm", function (e) {
        e.stopPropagation()
        project.scene = "view"
        let av = $(this).attr("action-view")
        let x = e.pageX
        project.cur_dom = this
        let menus = get_attr_menu(od[av])
        let events = od.events
        //对选中的值进行初始化
        let template =''
        if(events !== undefined && events !== "") {
            template += ` <fieldset><legend>事件</legend>${events}</fieldset>    `
        }
        if(menus !== undefined && menus !== "") {
            template += `<fieldset class = "style"><legend>操作</legend>${menus}</fieldset>`
        }

        template += `<fieldset class = "style"><legend>样式</legend>${od.style.menu.template}</fieldset>`
        //属性弹出菜单
        let dialog = new Dialog({
            title:"属性",
            style:{
                width:"360px",
                margin:"auto",
                left: x + 80 + "px"
            },
            template:template
        })
        dialog.show()

    })
    $(".preview-viewer").on("click",".styleditor",function(e) {
        e.stopPropagation()
        project.scene = "view"
        let av = $(this).attr("action-view")
        let x = e.pageX
        //属性弹出菜单
        let dialog = new Dialog({
            title:"样式",
            style:{
                width:"360px",
                margin:"auto",
                left: x + 80 + "px"
            },
            template:od.style.menu.template
        })
        dialog.show()
    })
}
export function onViewContentChange(project) {
    $(".preview-viewer").on("blur","[contenteditable=true]",(e) => {
        listen_content_change(e, project)
    })
}

export function onVueDataChange(project) {
    $("#vuedata").on("change",".data-box-value input",function(e){
        listen_data_change(e, project)
    })
}
function saveProject(project) {
    let content = project.solve()
    let origin = JSON.stringify(project.toJson())
    origin = origin.replace(/\\/g,'\\\\')
    content = content.replace(/\\/g, '\\\\').replace(/\'/g,'\\\\\\\'')
    return axios.post('/project/design',{
        content:content,
        origin:origin
    })
}

export function onMenuClick(project) {
    $('.save-prj').on('click',(e) => {
        let promise = saveProject(project)
        promise.then(res => {
            if(res.data.code === 0) {
                alert_success("保存成功")
            }else {
                alert_warning(res.msg)
            }
        }).catch(err => {
            alert_danger(JSON.stringify(err))
        })
    })
    $('.preview-prj').on('click',(e)=> {
        let promise = saveProject(project)
        promise.then(res => {
            if(res.data.code === 0) {
                new Dialog({
                    style:{
                        width:'320px',
                        height:'320px',
                        top:'0',
                        bottom:'0',
                        left:'0',
                        right:'0',
                        margin:'auto'
                    },
                    template:'<img src = "/project/preview" style = "width:100%;"></img>'
                }).show()
            }else {

            }
        }).catch(err => {
            alert_danger(JSON.stringify(err))
        })

    })
    $('.download-prj').on('click',(e) => {

    })
    $('.export-prj').on('click', (e) => {

    })
    $('.viewport-adjust').on('click', (e) => {

    })
    $('.orientation').on('click', (e) => {

    })
}

